<template>
    <view class="page-wrapper">
        <view class="plan-list">
            <up-swipe-action :atuoClose="true">
                <up-swipe-action-item v-for="item in dataList" :key="item.id" @click="removePlan" :options="options"
                    :name="item.id">
                    <view class="plan-item" >
                        <view class="info" @click="toEditItem(item)">
                            <view class="time">{{ item.time }}</view>
                            <view class="desc-text">&nbsp;{{ item.fenshu }}&nbsp;{{ $t('common.feedUnit') }}</view>
                        </view>
                        <view class="switch-wrapper">
                            <up-switch v-model="item.active" activeColor="#15B8A6" @change="changeSwitch(item)"></up-switch>
                        </view>
                    </view>
                </up-swipe-action-item>
            </up-swipe-action>
        </view>
        <view class="bottom-box shadow-top">
            <up-button @click="addPlan" icon="plus" :text="$t('pages.machine_plan.add_btn')" size="normal" type="primary" 
                style="width: 600rpx;" class="middle-round"></up-button>
        </view>

        <up-modal :title="$t('pages.machine_plan.remove_title')" :content="$t('pages.machine_plan.remove_desc')" :show="confirmRemove"
            showCancelButton :confirmText="$t('common.confirm')" confirmColor="#CC0000" :cancelText="$t('common.cancel')" closeOnClickOverlay
            @confirm="confirmDelete" @cancel="cancelDelete"></up-modal>

        <uni-popup ref="showBottom" type='bottom'>
            <view class="bottom-popup">
                <view class="top-row">
                    <text class="title">{{ $t('pages.machine_plan.AutomaticFeeding') }}</text>
                </view>
                <view class="picker-title">
                    <text>{{ $t('pages.machine_plan.time') }}</text>
                    <text>{{ $t('pages.machine_plan.feeding') }}</text>
                </view>
                <view class="picker-list">
                    <picker-view class="picker-wrapper" :value="selectedPickerIndex.time" indicator-style="height: 80rpx;" @change="onTimeChange">
                        <picker-view-column>
                            <view class="picker-item" v-for="item in timeHourArr" :key="item">{{ item }}</view>
                        </picker-view-column>
                        <picker-view-column>
                            <view class="picker-item">:</view>
                        </picker-view-column>
                        <picker-view-column>
                            <view class="picker-item" v-for="item in timeMinuteArr" :key="item">{{ item }}</view>
                        </picker-view-column>
                    </picker-view>

                    <picker-view class="picker-wrapper" :value="selectedPickerIndex.count" indicator-style="height: 80rpx;"
                        @change="onFeedNumChange">
                        <picker-view-column>
                            <view class="picker-item" v-for="item in 9" :key="item">{{ item }} {{ $t('common.feedUnit') }}</view>
                        </picker-view-column>
                    </picker-view>
                </view>

                <view class="bottom-button">
                    <up-button :text="$t('common.Feeding')" size="normal" type="primary" 
                        @click="debounceSubmit" class="bottom-button middle-round"></up-button>
                </view>
            </view>
        </uni-popup>

        <view class="empty-box" v-if="dataList.length === 0">
            <view class="row">
                {{ $t('pages.machine_plan.empty_title') }}
            </view>
            <view class="row">
                {{ $t('pages.machine_plan.empty_desc') }}
            </view>
            <view class="row">
                <image src="/static/icons/empty-plan.png" mode="aspect-Fit" class="empty-image"/>
            </view>
        </view>
    </view>
</template>

<script setup>
import { nextTick, reactive, ref, } from 'vue';
import { onLoad, onShow, } from '@dcloudio/uni-app';
import { navigateBack, CacheUtils, getCurrentDateOfMS, debounceFunction, } from '@/utils/index';
import {
		getClockListApi,
		addWeiShiApi,
		changeWeiShiApi,
		removeWeiSiApi,
	} from "@/api/request";
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const options = ref([{
    text: t('common.delete'),
    icon: 'trash-fill',
    style: {
        height: "100rpx",
        backgroundColor: "#f56c6c",
        fontSize: "26rpx",
        marginTop: "40rpx",
    },
},])

const dataList = ref([]);
const deviceId = ref('');
const confirmRemove = ref(false);
const deleteId = ref('');
const showBottom = ref(null);
const selectedPickerIndex = reactive({
    time: [0, 0, 0],
    count: [0],
});
const plan = reactive({
    num: 1,
    time: '00:00',
    id: '',
    fenzuid: '', // 分组id
    active: true, //是否开启
});
const timeHourArr = new Array(24).fill(0).map((item, index) => {
    return index < 10 ? `0${index}` : `${index}`;
});
const timeMinuteArr = new Array(60).fill(0).map((item, index) => {
    return index < 10 ? `0${index}` : `${index}`;
});
const hasShowErrorToast = ref(false); // 是否已经展示异常提示框


const showPupup = () => {
    showBottom.value?.open();
}
const hidePoup = () => {
    showBottom.value?.close();
    resetPlan();
}
const resetPlan = () => {
    plan.num = 1;
    plan.time = '00:00';
    plan.id = '';
    plan.active = false;
    plan.fenzuid = '';
	selectedPickerIndex.time = [ 0, 0, 0 ];
	selectedPickerIndex.count = [ 0 ];
}

const addPlan = () => {
	resetPlan();
	nextTick(()=>{
		showPupup();		
	})
}

const setSlectedPlan = (item)=>{
    plan.id = item.id;
    plan.fenzuid = item.fenzuid;
    const [ hour, minute ] = String(item.time).split(':');
    plan.time = `${hour}:${minute}`;
    plan.num = Number(item.fenshu);
    plan.active = item.active;
}

const toEditItem = (item)=>{
    setSlectedPlan(item);
    const [ hour, minute ] = String(item.time).split(':');
    const hourIndex = timeHourArr.findIndex((item) => item == hour);
    const miniteIndex = timeMinuteArr.findIndex((item) => item == minute);
    selectedPickerIndex.time = [ hourIndex, 0, miniteIndex ];
    selectedPickerIndex.count = [ plan.num-1 ];
	nextTick(()=>{
		showPupup();		
	})
}

const cancelDelete = () => {
    deleteId.value = '';
    confirmRemove.value = false;
}

const confirmDelete = async () => {
    let res = await removeWeiSiApi(deleteId.value)
    if (res.response.result == true) {
		const plan = dataList.value.find(el=>el.id==deleteId.value);
		if(!plan){
			return;
		}
		let paramss = {
			on: 0,	
			fenshu: plan.fenshu,
			xiaoshi:  res.time?res.time.hour:(plan.time.split(':')[0]),
			fenzhong: res.time?res.time.minute:(plan.time.split(':')[1]),
			fenzuid: plan.fenzuid,
		}
		uni.showLoading({
		    title: t('common.instructSendingTitle'),
		    mask: true,
		});
		uni.$emit('weishishijian', paramss)
		uni.$on("weishiPlanSuccess", () => {
		    uni.hideLoading()
		});
		uni.$once('weishiPlanError', () => {
		    uni.hideLoading()            
		    !hasShowErrorToast.value && uni.showModal({
		        title: t('common.instructFailedTitle'),
		        showCancel: false,
		        content: t('common.instructFailedDesc'),
				success(){
					hasShowErrorToast.value = false;					
				},
		    });
			setTimeout(()=>{
				hasShowErrorToast.value = true;				
			},200);
		});
		
        cancelDelete();
        getList();
    } else {
        uni.showToast({
            title: res.response.msg,
            icon: 'none'
        })
    }
}

const getList = async () => {
    let query = {
        userid: CacheUtils.get('userid'),
        imei: deviceId.value,
    }
    let res = await getClockListApi(query)
    if (res.response.result == true) {
         dataList.value = (res.list||[]).map((el) => ({
            ...el,
            active: el.on == 1 ? true : false,
        }));
    } else {
        dataList.value = []
    }
}

const removePlan = (event) => {
    deleteId.value = event.name;
    confirmRemove.value = true;
}

const onFeedNumChange = ({ detail }) => {
    plan.num = detail.value[0] + 1;
}
const onTimeChange = ({ detail }) => {
    plan.time =  timeHourArr[detail.value[0]] + ':' + timeMinuteArr[detail.value[2]];
}

// 开关状态切换
const changeSwitch = (item) => {
    setSlectedPlan(item);
    debounceSubmit();
}

const submit = async () => {
    let query = {
        userid: CacheUtils.get('userid'),
        imei: deviceId.value,
        time: plan.time,
        week: '',
        fenshu: plan.num,
        remark:  '',
        on: plan.active ? 1 : 0,
        fenzuid: plan.fenzuid,
        date: getCurrentDateOfMS( Number(plan.time.split(':')[0]), Number(plan.time.split(':')[1]) ),
    }

    let res = {};
    if(plan.id){
        query.id = plan.id;
        // update
        res = await changeWeiShiApi(query)
    }else{
        // add
		query.on = 1;
        query.fenzuid = dataList.value.length>0?(dataList.value[0].newfenzuid||dataList.value[0].fenzuid):1;
		res = await addWeiShiApi(query)
    }

    if (res.response.result == true) {
        let paramss = {
            on: query.on,
            fenshu: query.fenshu,
            xiaoshi: query.time.split(':')[0],
            fenzhong: query.time.split(':')[1],
            fenzuid: query.fenzuid,
        }

        uni.showLoading({
            title: t('common.instructSendingTitle'),
            mask: true,
        });
        uni.$emit('weishishijian', paramss)
        uni.$on("weishiPlanSuccess", () => {
            uni.hideLoading()
        });
        uni.$once('weishiPlanError', () => {
            uni.hideLoading()            
            !hasShowErrorToast.value && uni.showModal({
                title: t('common.instructFailedTitle'),
                showCancel: false,
                content: t('common.instructFailedDesc'),
        		success(){
        			hasShowErrorToast.value = false;					
        		},
            });
        	setTimeout(()=>{
        		hasShowErrorToast.value = true;				
        	},200);
        });
        hidePoup();
        getList();
    } else {
        uni.showToast({
            title: res.response.msg,
            icon: 'none'
        })
    }
}
const debounceSubmit = debounceFunction(submit);

onLoad((query) => {
    deviceId.value = query.imei;
});
onShow(() => {
    getList();
});
</script>

<style lang="scss" scoped>
$bottom-box-height: 100rpx;

.page-wrapper {
    position: relative;
    padding-bottom: $bottom-box-height;
    box-sizing: border-box;
    background-color: #FFFFFF;

    .bottom-box {
		background-color: #FFFFFF;
        bottom: 0rpx;
        left: 0rpx;
        right: 0rpx;
        position: fixed;
        display: flex;
        justify-content: center;
        align-items: center;
        height: $bottom-box-height;
        box-sizing: border-box;
    }
}

.plan-list {
    padding: 30rpx;
    display: flex;
    flex-direction: column;
    row-gap: 20rpx;

    .plan-item {
        margin-bottom: 20rpx;
        padding: 30rpx 40rpx;
        // background-color: #FFFFFF;
        display: flex;
        align-items: center;
        column-gap: 10rpx;
        border-radius: 20rpx;
        overflow: hidden;
        box-shadow: 0px 2px 4px 0px rgba(0,0,0,0.1);

        .info {
            flex: 1;

            .time {
                font-size: 60rpx;
                color: #000000;
            }
        }

        .switch-wrapper {
            width: 120rpx;
        }
    }
}

.empty-box {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    height: 400rpx;
    padding: 60rpx;

    .row {
        display: flex;
        align-items: center;
        line-height: 1;
        margin-bottom: 8rpx;
    }
    .empty-image{
        width: 242rpx;
        height: 242rpx;
    }
}

.bottom-popup {
    width: 750rpx;
    height: 700rpx;
    padding: 0 20rpx;
    border-radius: 40rpx 40rpx 0 0;
    background-color: #fff;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    text-align: center;
    row-gap: 10rpx;

    .devide{
        width: 700rpx;
    }

    .top-row {
        margin-top: 20rpx;
        display: flex;
        justify-content: space-between;

        .title {
            flex: 1;
            text-align: center;
            font-size: 40rpx;
        }

    }

    .picker-list{
        display: flex;
        column-gap: 12rpx;
        justify-content: space-between;
    }
    .picker-title{
        display: flex;
        width: 600rpx;
        justify-content: space-around;
        color: #4B5563;
        font-size: 28rpx;
    }
    .picker-wrapper {
        position: relative;
        margin-top: 30rpx auto;
        height: 400rpx;
        width: 300rpx;
        text-align: center;
        overflow: hidden;

        .picker-item {
            display: flex;
            align-items: center;
            justify-content: center;
        }

    }

    .bottom-button {
        padding: 10rpx 20rpx;

        .bottom-button {
            margin: 0 auto;
            width: 600rpx;
        }
    }
}

.picker-title {
    font-size: 36rpx;
    line-height: 1;
    font-weight: bold;
}

:deep(.u-swipe-action-item__content) {
    background-color: #FFFFFF;
}


.bottom-box:deep(.u-icon){
    margin-right: 10rpx;
}
</style>